/*
 * Copyright 2018 the original author or authors.
 * 
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 * 
 * 
 * 
 * 
 */
 
package org.demo.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.demo.util.bean.HttpResultBean;


/**
 * 封装 网络连接工具。
 * @author jx-air
 * @date 2018年2月1日 下午3:18:23
 * @version 1.0
 */
public abstract class ExaHttpClient {
	
	private static final String DEFAULT_CHARSET = "UTF-8";//默认编码方式

	/**
	 *  http get请求
	 * @param url
	 * @return
	 */
	public static HttpResultBean get(String url) {
		
		return get(url,null);
	}
	
	/**
     * http get请求
     * @param url 请求地址
     * @param para 请求参数
     * @return
     */
	public static HttpResultBean get(String url,Map<String,String> paraMap) {
		long startTime = System.currentTimeMillis();//统计用时
		HttpResultBean result = new HttpResultBean();//封装返回结果
		
		try {
			//拼接get请求参数
			if(paraMap !=null && paraMap.size() > 0) {
				StringBuffer tempUrl = new StringBuffer();
				for (Entry<String,String> entry : paraMap.entrySet()) {
					tempUrl.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
				}
				url = url +"?" + tempUrl.substring(0,tempUrl.length()-1);
			}
			
			System.out.println("http get请求接口调用,请求地址:" + url);
			System.out.println("http get请求接口调用,请求参数:" + paraMap);
			HttpGet httpGet = new HttpGet(url);
			CloseableHttpClient httpClient = HttpClients.createDefault();
			CloseableHttpResponse response = httpClient.execute(httpGet);
			
			//判断返回结果
			if(response.getStatusLine().getStatusCode() ==HttpStatus.SC_OK) {
				result.succ();
				String res = EntityUtils.toString(response.getEntity(),DEFAULT_CHARSET);// 返回json格式:
				result.setResponse(res);
			}else {
				System.err.println("http get请求接口调用,错误,错误代码:" + response.getStatusLine().getStatusCode());
			}
			
			System.out.println("http get请求接口调用,返回结果:"+result.isStatus()+",返回报文:" + result.getResponse());
			System.out.println("http get请求接口调用,用时:" + ExaTimeUtil.useTime(startTime) + "秒");
		}  catch (Exception e) {
			String useTime = ExaTimeUtil.useTime(startTime);
			System.err.println("http get请求接口调用,异常,用时:" + useTime + "秒");
			System.err.println("http get请求接口调用,异常信息:" +e.getMessage());
			e.printStackTrace();
		}
		
		return result;
	}
	
	/**
	 * 模拟页面form提交表单
	 * @param url 请求地址
	 * @param paraMap 请求参数
	 * @return
	 */
	public static HttpResultBean postForm(String url,Map<String,String> paraMap) {
		long startTime = System.currentTimeMillis();//统计用时
		HttpResultBean result = new HttpResultBean();//封装返回结果
		
		try {
			List <NameValuePair> nvps = new ArrayList <NameValuePair>();
			//封装post请求参数
			if(paraMap !=null && paraMap.size() > 0) {
				for (Entry<String,String> entry : paraMap.entrySet()) {
					String key = entry.getKey();
					String value=entry.getValue();
					nvps.add(new BasicNameValuePair(key, value));
					
				}
			}
			System.out.println("http post form请求接口调用,请求地址:" + url);
			System.out.println("http post form请求接口调用,请求参数:" + paraMap);
			
			HttpPost httpPost = new HttpPost(url);
			CloseableHttpClient httpClient = HttpClients.createDefault();
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			
			CloseableHttpResponse response = httpClient.execute(httpPost);
			//判断返回结果
			if(response.getStatusLine().getStatusCode() ==HttpStatus.SC_OK) {
				result.succ();
				String res = EntityUtils.toString(response.getEntity(),DEFAULT_CHARSET);// 返回json格式:
				result.setResponse(res);
			}else {
				System.err.println("http get请求接口调用,错误,错误代码:" + response.getStatusLine().getStatusCode());
			}
			
			System.out.println("http post form请求接口调用,返回结果:"+result.isStatus()+",返回报文:" + result);
			System.out.println("http post form请求接口调用,用时:" + ExaTimeUtil.useTime(startTime) + "秒");
		} catch (Exception e) {
			String useTime = ExaTimeUtil.useTime(startTime);
			System.err.println("http post form请求接口调用,异常,用时:" + useTime + "秒");
			System.err.println("http post form请求接口调用,异常信息:" +e.getMessage());
			e.printStackTrace();
		}
		return result;
	}
	
}
